//
//  HBSetTradpasswordCtrl.m
//  HuoBao
//
//  Created by 于会海 on 15/12/3.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBSetTradpasswordCtrl.h"
#import "HBChangePaw.h"
#import "HBWithdrawCtrl.h"
#import "HBUserDistillInfo.h"
#import "HBUserDistillParam.h"
#import "HBUserDistillParser.h"
#import "HBSetTradingPwdParam.h"
#import "HBSetTradingPwdParser.h"
#import "NSString+MKNetworkKitAdditions.h"
#import "HBGetUserInfoManager.h"
#import "HBLoginUserInfo.h"
#import "CustomCopySuccess.h"


@interface HBSetTradpasswordCtrl ()<UITextFieldDelegate>
{
    NSString*    password;
    NSString*    rePassword;
    NSArray*     codeImageArr;
    UITextRange* previousSelection;
    NSString*    previousTextFieldContent;
    int          isFirstPassword;
}
- (IBAction)confirmClickedAction:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UILabel *alertLabel;
@property (strong, nonatomic)  UITextField *passwordField;
@property (weak, nonatomic) IBOutlet UILabel *topTitleLabel;
@property (weak, nonatomic) IBOutlet UIImageView *secPassword;
@property (weak, nonatomic) IBOutlet UIView *passwordBackView;
@property (weak, nonatomic) IBOutlet UIImageView *firstPassword;
@property (weak, nonatomic) IBOutlet UIImageView *thirdPassword;
@property (weak, nonatomic) IBOutlet UIImageView *fifthPassword;
@property (weak, nonatomic) IBOutlet UIImageView *sixthPassword;
@property (weak, nonatomic) IBOutlet UIImageView *fourthPassword;

@end

@implementation HBSetTradpasswordCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
    [self makeStatusEmpty];
    isFirstPassword = 0;
}

- (void)buildLayout{
    [super buildLayout];
  

//    self.confirmBtn.layer.cornerRadius = 4.0;
//    /*
//     [_bugBtn setBackgroundColor:[LCCommon getColor:@"f34546"] forState:UIControlStateNormal];
//     [_bugBtn setBackgroundColor:[LCCommon getColor:@"d43333"] forState:UIControlStateHighlighted];
//     */
//    [self.confirmBtn setBackgroundColor:[LCCommon getColor:@"d43333"] forState:UIControlStateHighlighted];
//    [self.confirmBtn setBackgroundColor:[LCCommon getColor:@"f24545"] forState:UIControlStateNormal];
//    [self.confirmBtn setBackgroundColor:[LCCommon getColor:@"bd3737"] forState:UIControlStateDisabled];
//    self.confirmBtn.enabled = NO;
//    [self.confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
//    [self.confirmBtn setTitleColor:[LCCommon getColor:@"ffffff"] forState:UIControlStateNormal];
//    [self.confirmBtn setTitleColor:[LCCommon getColor:@"fd7a7a"] forState:UIControlStateDisabled];
    
    
    [self creatUI];
}

- (void)doDone{
    [self goToPawVC];
}

- (void)goToPawVC{
    
    
    //退栈至指定页面
    for(UIViewController *controller in self.navigationController.viewControllers) {
        if([controller isKindOfClass:[HBChangePaw class]]){
            HBChangePaw* pawVC = (HBChangePaw *)controller;
            [self.navigationController popToViewController:pawVC animated:YES];
        }
    }
}

- (void)goToTiXianVC{
    //退栈至指定页面
    for(UIViewController *controller in self.navigationController.viewControllers) {
        if([controller isKindOfClass:[HBWithdrawCtrl class]]){
            HBWithdrawCtrl* tixianVC = (HBWithdrawCtrl *)controller;
            [self.navigationController popToViewController:tixianVC animated:YES];
        }
    }
}

- (void)doBack{
    LLog(@"点击返回按钮");
    [self makeStatusEmpty];
    //退栈至指定页面
    for(UIViewController *controller in self.navigationController.viewControllers) {
        if([controller isKindOfClass:[HBWithdrawCtrl class]]){
            HBWithdrawCtrl* tixianVC = (HBWithdrawCtrl *)controller;
            [self.navigationController popToViewController:tixianVC animated:YES];
        }
    }
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
       codeImageArr = @[self.firstPassword,self.secPassword,self.thirdPassword,self.fourthPassword,self.fifthPassword,self.sixthPassword];
    [self allPasswordEmpty];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    
    self.passwordField = [[UITextField alloc] initWithFrame:self.passwordBackView.frame];
    self.passwordField .autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
    self.passwordField .borderStyle = UITextBorderStyleNone;
    self.passwordField .secureTextEntry = YES;
    self.passwordField .keyboardType = UIKeyboardTypeNumberPad;
    [self.passwordField  addTarget:self action:@selector(passwordBackView:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:self.passwordField];
    [self.passwordField setHidden:YES];
    [self.passwordField setDelegate:self];
    [self.passwordField becomeFirstResponder];

}

- (void)makeLeftButtonApear:(BOOL)isApear{
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    if (isApear == NO) {
        UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
        self.navigationItem.leftBarButtonItem = leftItem;
        
    }else{
        leftBtn.frame = CGRectMake(0, 0, 13, 22);
        [leftBtn setBackgroundImage: [UIImage imageNamed:@"bank_back"] forState:UIControlStateNormal];
        UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
        [leftBtn addTarget:self action:@selector(doBack) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.leftBarButtonItem = leftItem;
    }
}

- (void)makeStatusEmpty{
    NSString* titleString;
    NSString* status = [HBLoginManager sharedHBLoginManager].currentUserInfo.tradingPwdStatus;
    LLog(@"%@",status);
    if ([status isEqualToString:@"0"]) {
        if (self.isFromTiXian == YES) {
             titleString = @"请设置提现密码";
        }else{
           
            titleString = @"请设置提现密码";
        }
    }else if([status isEqualToString:@"1"]){
        if (self.isFromTiXian == YES) {
            titleString = @"重置提现密码";
        }else{
            titleString = @"重置提现密码";
        }
    }else{
        titleString = @"设置提现密码";
    }
    self.title = titleString;
    self.topTitleLabel.text = titleString;
    if (!(self.isFromTiXian == YES)) {
        [self showDoneWithTitle:@"取消"];
        [self makeLeftButtonApear:NO];
    }else {
        [self makeLeftButtonApear:YES];
    }
    [self.passwordField setText:@""];
    [self.alertLabel setText:@""];
    [self allPasswordEmpty];
    isFirstPassword = 0;
}

- (void)creatUI{
    [self makeStatusEmpty];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    previousTextFieldContent = textField.text;
    previousSelection = textField.selectedTextRange;
    
    if ([string isEqualToString:@"\n"]){
        return YES;
    }
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if ([toBeString length] > 6) {
        return NO;
    }
    return YES;
}

- (void)passwordBackView:(UITextField*)textfield{
    self.alertLabel.text = @"";
    NSString *text = self.passwordField.text;
    //第几次输入
    NSUInteger targetCursorPosition =[textfield offsetFromPosition:textfield.beginningOfDocument toPosition:textfield.selectedTextRange.start];
    
    NSString* nStr = textfield.text;
    NSString* preTxt = [previousTextFieldContent stringByReplacingOccurrencesOfString:@" " withString:@""];
   // UITextField* textFieldChild = codeImageArr[targetCursorPosition];
    char editFlag = 0;
    LLog(@"%lu",(unsigned long)codeImageArr.count);
    
    if (nStr.length <= preTxt.length) {
        editFlag = 0;
        UIImageView* imageView = codeImageArr[targetCursorPosition];
        LLog(@"删除第%li个",(long)targetCursorPosition);
        imageView.hidden = YES;
    }else {
        UIImageView* imageView = codeImageArr[targetCursorPosition-1];
        editFlag = 1;
        LLog(@"增加第%li个",(long)targetCursorPosition);
        imageView.hidden = NO;
    }
    if ([text length] == 6) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           
            if (isFirstPassword ==0) {
                password = self.passwordField.text;
                [self makeLeftButtonApear:YES];
                [self.topTitleLabel setText:@"请再次输入密码"];
                isFirstPassword = 1;
                LLog(@"第一次输入的密码%@",password);
                [self allPasswordEmpty];
                [self.passwordField setText:@""];
            }else if (isFirstPassword == 1){
                rePassword = self.passwordField.text;
                LLog(@"第二次输入的密码%@",rePassword);
                if ([password isEqualToString:rePassword]) {
                    LLog(@"两次输入一致");
                    
                   CustomCopySuccess* sucessView = [[CustomCopySuccess alloc] initWithCopyBtnOraginY:self.alertLabel.origin.y nameString:@"设置成功"];
                    
                    [sucessView showSuccessAlertView];
                    if (self.isFromTiXian == YES) {
                        [self requestToSetTradingPwd];
                    }else {
                        [self requestToSetTradingPwd];
                    }
                    
                }else{
                    LLog(@"两次输入不一致，请重新输入");
                    isFirstPassword = 0;
                    [self.topTitleLabel setText:@"请设置提现密码"];
                    self.alertLabel.text = @"两次输入不一致，请重新输入";
                    [self allPasswordEmpty];
                    [self.passwordField setText:@""];
                }
            }
           
          
        });
        
    }
}
- (void)requestToSetTradingPwd{
    HBSetTradingPwdParam* param = [[HBSetTradingPwdParam alloc] init];
    HBSetTradingPwdParser* parser = [[HBSetTradingPwdParser alloc] init];
    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
    param.tradingPwd = self.passwordField.text.md5;
    [NetCenter postDataFromURL:Method_setTradingPwd params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0) {
            LLog(@"提现密码设置成功");

            [HBGetUserInfoManager requestToGetUserInfoWithResult:^(BOOL isSuccess, NSString *msg, NSError *error) {
                
            }];
            if (self.isFromTiXian) {
                [self requestToGetDistillInfo];
            }else{
                [self goToPawVC];
            }
            

        }else{
            DISSMISS_ERR(myResult.message);
        }
        } failure:^(NSError *error) {
            DISSMISS_ERR(error.description);
        }];

}


-(void)requestToGetDistillInfo{
    [CustomLoadingView showHudToView:self.view];
    HBUserDistillParam *param = [[HBUserDistillParam alloc]init];
    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
    HBUserDistillParser *parser = [[HBUserDistillParser alloc]init];
    [NetCenter postDataFromURL:Method_userDistill params:param parser:parser result:^(ParserResult *myResult) {
        //        [CustomLoadingView hideHudForView:nil];
        [CustomLoadingView hideHudForView:self.view];
        if (myResult.code == 0)
        {
            HBUserDistillInfo *info = (HBUserDistillInfo *)myResult.result;
                HBWithdrawCtrl *expofCtrl = [[HBWithdrawCtrl alloc]init];
                expofCtrl.userDistillInfo = info;
                [self.navigationController pushViewController:expofCtrl animated:YES];
        }
        else
        {
            DISSMISS_ERR(myResult.message);
        }
        
    } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
        DISSMISS_ERR([error description]);
    }];
    
}

- (void)allPasswordEmpty{
    for (UIImageView* imageView in codeImageArr) {
        [imageView setHidden:YES];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)confirmClickedAction:(UIButton *)sender {
    LLog(@"确定");
    
}

@end
